const { src, dest, series, parallel, watch } = require('gulp');
const bs = require('browser-sync').create();
const del = require('del');
const cleanScripts = require('gulp-uglify');
const cleanHtml = require('gulp-htmlmin');
const cleanCss = require('gulp-clean-css');
const gIf = require('gulp-if');
const rename = require('gulp-rename');
const sass = require('gulp-sass');
const babel = require('gulp-babel');
const swig = require('gulp-swig');
const useref = require('gulp-useref');
// const imagemin = require('gulp-imagemin');


function clean() {
  return del(['dist', 'temp']);
}

function style() {
  return src('src/assets/styles/*.scss', { base: 'src' })
    .pipe(sass({ outputStyle: 'expanded' }))
    .pipe(dest('temp'));
}

function script() {
  return src('src/assets/scripts/*.js', { base: 'src' })
    .pipe(babel({
      presets: ['@babel/preset-env']
    }))
    .pipe(dest('temp'));
}

function template() {
  return src('src/*.html', { base: 'src' })
    .pipe(swig())
    .pipe(dest('temp'));
}

function image() {
  return src('src/assets/images/**', { base: 'src' })
    .pipe(dest('dist'));
}

function font() {
  return src('src/assets/fonts/**', { base: 'src' })
    .pipe(dest('dist'));
}


function copy() {
  return src('public/**')
    .pipe(dest('dist/public'));
}

function ur() {
  return src('temp/**/*.html', { base: 'temp' })
    .pipe(useref({ searchPath: ['temp', '.'] })) // 和baseDir类似
    .pipe(gIf(/\.js$/, cleanScripts()))
    .pipe(gIf(/\.css$/, cleanCss()))
    .pipe(gIf(/\.html$/, cleanHtml()))
    .pipe(dest('dist'));
}

function watchBuild() {
  watch('src/assets/styles/*.scss', style);
  watch('src/assets/scripts/*.js', script);
  watch('src/*.html', template);
  // watch('src/assets/images/**', image);
  // watch('src/assets/fonts/**', font);
  // watch('public/**', copy);
  watch(['src/assets/styles/*.scss', 'src/assets/scripts/*.js', 'public/**'], bs.reload);
}

function server() {
  watchBuild();
  bs.init({
    open: false,
    notify: false,
    files: "dist/**",
    server: {
      // 开发阶段，像图片、字体和静态文件，没必要编译，所以直接会指向源码
      baseDir: ['temp', 'src', 'public'],
      routes: { // 优先级高于baseDir
        '/node_modules': './node_modules'
      }
    }
  });
}


const compile = parallel(script, style, template);
const build = series(clean, parallel(series(compile, ur), image, font, copy));
const dev = series(compile, server);

module.exports = {
  build,
  dev,
  clean
}
